<template>
  <div class="password-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>

      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="120px"
        @submit.prevent="submitForm"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="form.oldPassword" 
            type="password" 
            show-password
            placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="form.newPassword" 
            type="password" 
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="form.confirmPassword" 
            type="password" 
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref , computed } from 'vue';
import { ElMessage } from 'element-plus';
import { updatePassword } from '@/api/password';
import { useStore } from 'vuex'; 


const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const validateConfirm = (rule, value, callback) => {
  if (value !== form.value.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirm, trigger: 'blur' }
  ]
};

const formRef = ref(null);

const store = useStore();

// 获取用户 ID（自动响应式更新）
console.log(store.state.user.userInfo.id)
const userId = store.state.user.userInfo.id

const submitForm = async () => {
  // 检查用户是否登录
  if (!userId) {
    ElMessage.error('请先登录');
    return;
  }

  // 表单验证
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updatePassword(userId, {
          newPassword: form.value.newPassword
        });
        ElMessage.success('密码修改成功');
        formRef.value.resetFields();
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '修改失败');
      }
    }
  });
};

const resetForm = () => {
  formRef.value.resetFields();
};
</script>

<style scoped>
.password-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.box-card {
  margin-top: 20px;
}
</style>
